#include <iostream>
#include <string>
#include "Reactor.hpp"
#include "Listener.hpp"
#include "Common.hpp"
#include "Log.hpp"
#include "NetCal.hpp"
#include "Protocol.hpp"

using namespace std;
using namespace LogModule;

static void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = stoi(argv[1]);
    Enable_Console_Log_Strategy(); // 启用控制台输出
    // 顶层业务模块
    shared_ptr<Cal> cal = make_shared<Cal>();

    // 构造协议对象
    shared_ptr<Protocol> protocol = make_shared<Protocol>([&cal](Request &req) -> Response
    { 
        return cal->Execute(req); 
    });

    // connection管理listen连接模块 间接创建channel(进行io)模块
    shared_ptr<Connection> conn = make_shared<Listener>(port);
    conn->RegisterHandler([&protocol](string &inbuffer) -> string
    {
        string response_str;
        while (true)
        {
            string package;
            if (!protocol->Decode(inbuffer, &package)) // 判断报文完不完整
                break;
            response_str += protocol->Execute(package);
        }
        LOG(LogLevel::DEBUG) << "结束匿名函数中...: " << response_str;
        return response_str;
    });

    // rector基座 事件派发
    unique_ptr<Reactor> tsvr = make_unique<Reactor>();

    tsvr->AddConnection(conn);
    tsvr->Loop();
    return 0;
}